package my.merborn.ordersysteam105.controllers;

import my.merborn.ordersysteam105.models.dao.UserMapper;
import my.merborn.ordersysteam105.models.pojo.User;
import my.merborn.ordersysteam105.models.pojo.enums.Power;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "adminFilter",urlPatterns = "/admin/*")
public class AdminFilter implements Filter {

    @Resource
    UserMapper um;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("admin filter start");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //System.out.println("request catched by admin fliter");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Integer uid = null;
        HttpSession session = req.getSession();
        session.getAttribute("uid");
        try{
            uid = (Integer) session.getAttribute("uid");
        }catch (Exception e){
            System.out.println("cause error by admin filter");
            resp.sendRedirect("http://localhost:8080/userlogin.html");
        }

        if (uid == null) {
            System.out.println("admin filter : uid is null !");
            try {
                resp.sendRedirect("http://localhost:8080/userlogin.html");
            }catch (Exception e){
                System.out.println("admin filter sendRedirect cause a problem ,so use the requestDispatcher,if" +
                        "also cause problem , please check the system admin !");
                req.getRequestDispatcher("userlogin.html").forward(req,resp);
            }

        } else {
            User user = um.selectByPrimaryKey(uid);
            if (Power.ADMIN.getPower().equals(user.getuPower())) {
                System.out.println("user is admin ");
                chain.doFilter(req, resp);
            } else {
                System.out.println("admin filter : not admin!");
                resp.sendRedirect("http://localhost:8080/userlogin.html");
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("warn ! + admin filter is destoryed,if you turn off the server,please miss this message");
    }
}
